package org.zebra.beansearch;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.PageUtil;
import cn.zhxu.bs.SearchResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.zebra.common.core.BaseResponseBodyAdviceChain;
import org.zebra.common.core.Result;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * beansearch 分页规范化输出
 *
 * @author zhanghongbin
 */
public class BeanSearchBaseResponseBodyAdviceChain extends BaseResponseBodyAdviceChain {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter returnType,
            MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request,
            ServerHttpResponse response) {
        if (returnType.getParameterType().isAssignableFrom(SearchResult.class)) {
            Result result = (Result) body;
            SearchResult searchResult = (SearchResult) result.getData();
            ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpServletRequest = servletServerHttpRequest.getServletRequest();
            String sizeStr = httpServletRequest.getParameter("size");
            String pageStr = httpServletRequest.getParameter("page");
            int size = 0;
            int page = 0;
            int pages = 0;
            if (NumberUtil.isInteger(sizeStr) && NumberUtil.isInteger(pageStr)) {
                size = Integer.parseInt(sizeStr);
                page = Integer.parseInt(pageStr);
                pages = PageUtil.totalPage(searchResult.getTotalCount().longValue(), size);
            }
            Map<String, Object> r = new HashMap<>();
            r.put("total", searchResult.getTotalCount().longValue());
            r.put("size", size);
            r.put("current", page);
            r.put("pages", pages);
            r.put("records", searchResult.getDataList());
            result.setData(r);
            return result;
        }
        return body;
    }
}
